package com.test.controller;

import com.test.pojo.FoodType;
import com.test.service.FoodTypeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


@Controller
public class FoodTypeCtrl {
    @Resource
    private FoodTypeService foodTypeService;
    /*
    *获取所有的菜系
    */
    @RequestMapping("/getAllFoodType")
    public String getAllFoodType(Model model){
        List<FoodType> foodTypeList = foodTypeService.getAllFoodType();
        model.addAttribute("foodTypeList",foodTypeList);
        return "FoodTypeList";
    }

    @RequestMapping("/gotoIndex")
    public String gotoIndex(Model model){
        return "index";
    }

    /*int
    *跳转到菜系更新页面
    **/
    @GetMapping(value = "/editFoodType")
    public String searchFoodTypeByID(@RequestParam("foodTypeId") int id, Model model){

       FoodType foodType = foodTypeService.getFoodTypeByID(id);

        if (foodType != null) {
            model.addAttribute("foodType",foodType);
            return "EditFoodType";
        }else {
            return "redirect:/getAllFoodType";
        }
    }

    /*
     * 更改菜系名称
     * */
    @PostMapping(value ="/doEditFoodType/{id}")
    public String doEditFoodType(@PathVariable("id") int id, FoodType foodType,Model model){

        int num = foodTypeService.updateFoodType(foodType);
        if(num > 0){
            model.addAttribute("msg","菜系更新成功！");
        }else{
            model.addAttribute("msg","菜系更新失败！");
        }
        return "forward:/getAllFoodType";
    }

    /*删除菜系*/
    @RequestMapping(value ="/delFoodType/{id}",method = RequestMethod.GET)
    public String delFoodType(@PathVariable("id") int id,Model model){
        int num = foodTypeService.deleteFoodType(id);
        System.out.println(num);
        if(num > 0){
            model.addAttribute("msg","菜系删除成功！");
        }else if (num == -1){
            model.addAttribute("msg","有菜品属于此菜系，所以不能删除该菜系");
        }else{
            model.addAttribute("msg","菜系删除失败！");
        }
        return "forward:/getAllFoodType";
    }

    /*
    * 转到添加页面
    * */
    @GetMapping(value = "/goToAddFootType")
    public  String goToAddFootType(){
        return "AddFoodType";
    }

    /*
    * 添加菜系
    **/
    @PostMapping(value ="/doAddFootType")
    public String addFootType(FoodType foodType,Model model){

        int num = foodTypeService.addFoodType(foodType);
        if(num > 0){
            model.addAttribute("msg","菜系【"+foodType.getTypeName()+"】添加成功！");
        }else{
            model.addAttribute("msg","菜系添加失败！");
        }
        return "forward:/getAllFoodType";
    }
}
